/**
 * 描述：系统首页框架
 * 日期：2019-07-24
 **/

(function(KIT, RES) {
  "use strict";
  var E = rapid.html.Element;
  var URL_TO_LOGIN = "/toLogin",
    URL_LOGOUT = RES.URL_ROOT + "/logout",
    URL_LOAD_MENU = RES.URL_ROOT + "/findModuleAndApp";

  var LEVEL_CLASS = ["", "nav-second-level", "nav-third-level"];

  var _initPwdDv = function() {
    rapid("#frmUpdateMyPwd").dataview({
      fields: [{
        title: "输入原密码", name: "oldPwd", editor: {
          mode: "password"
        }
      }, {
        title: "输入新密码", name: "newPwd", editor: {
          mode: "password"
        }
      }, {
        title: "再输入一次新密码", name: "confirmPwd", editor: {
          mode: "password"
        }
      }]
    });
  };

  var _initMenusHtml = function(children, level) {
      if(level > 1) {
        rapid._error_("H+最多只支持3级导航样式。");
        return "";
      }

      var __len;
      if(rapid.isEmpty(children) || (__len = children.length) === 0) {
        return "";
      }

      var __html = level === 0 ? "" : "<ul style=\"background: #0d5aa7\" class=\"nav " + LEVEL_CLASS[level] + " collapse\">",
        __child, __name, __path;

      for(var __i = 0; __i < __len; __i++) {
        __child = children[__i];
        __name = __child.text.split("|");

        if(__name.length == 2) {
          __path = __name[1];
          __name = __name[0];
        } else {
          __name = __name[0];
          __path = "#";
        }

/*        if(__path.indexOf("?") != -1) {
          __path += "&title=" + __name;
        } else {
          __path += "?title=" + __name;
        }*/

        if(rapid.isEmpty(__child.children)) {
          __html += E.li(
            E.a({cssClass: "J_menuItem", href: __path},
              E.span({cssClass: "nav-label"}, __name)
            )
          );

        } else {
          __html += E.li(
            E.a(
              E.span({cssClass: "nav-label"}, __name),
              E.span({cssClass: "fa arrow"})
            ),
            _initMenusHtml(__child.children, level + 1)
          );
        }
      }
      __html += level === 0 ? "" : "</ul>";

      return __html;
    },
    _updatePwd = function() {
      var __dv = rapid("#frmUpdateMyPwd").dataview(),
        __ui_old = __dv.ui("oldPwd"),
        __ui_new = __dv.ui("newPwd"),
        __ui_confirm = __dv.ui("confirmPwd"),
        __old = __ui_old.val(),
        __new = __ui_new.val(),
        __confirm = __ui_confirm.val();

      //region 错误检测
      if(rapid.isEmpty(__old)) {
        rapid.info("请填写原密码。", function() {
          __ui_old.focus();
        });
        return false;
      }
      if(rapid.isEmpty(__new)) {
        rapid.info("请填写原密码。", function() {
          __ui_new.focus();
        });
        return false;
      }
      if(rapid.isEmpty(__confirm)) {
        rapid.info("请再输入一遍新密码。", function() {
          __ui_confirm.focus();
        });
        return false;
      }
      if(__new !== __confirm) {
        rapid.warning("两次输入的新密码不一致。", function() {
          __ui_confirm.focus();
        });
        return false;
      }
      if(__old === __new) {
        rapid.warning("新密码不可与原密码一样。", function() {
          __ui_new.focus();
        });
        return false;
      }
      //endregion

      var __wnd = this;
      rapid.post({
        url: RES.URL_ROOT + "/updateUserPwd",
        data: "oldPwd=" + __old + "&newPwd=" + __new + "&confirmPwd=" + __confirm,
        fail: function() {
          __ui_old.focus();
        },
        success: function() {
          rapid.success("修改成功。", function() {
            __wnd.hide();
          });
        }
      });
    };

  // var _openPage = function(href) {
  //   var __menu = rapid("#side-menu").find("[href='" + href + "']");
  //   if(__menu.length === 0) {
  //     return;
  //   }
  //
  //   var __index = __menu.data("index"),
  //     __name = __menu.children().text();
  //
  //   var str = '<a href="javascript:;" class="active J_menuTab" data-id="' + href + '">' + __name + ' <i class="fa fa-times-circle"></i></a>';
  //   $('.J_menuTab').removeClass('active');
  //
  //   // 添加选项卡对应的iframe
  //   var str1 = '<iframe class="J_iframe" name="iframe' + __index + '" width="100%" height="100%" src="' + href +
  //              '" frameborder="0" data-id="' + href + '" seamless></iframe>';
  //   $('.J_mainContent').find('iframe.J_iframe').hide().parents('.J_mainContent').append(str1);
  //   $('.J_menuTabs .page-tabs-content').append(str);
  //   //scrollToTab($('.J_menuTab.active'));
  // };

  var _loadMenus = function() {
      rapid.post({
        url: URL_LOAD_MENU,
        async: false,
        fail: function() {
          window.top.location.href = URL_TO_LOGIN;
        },
        success: function(items) {
          if(rapid.isEmpty(items)) {
            rapid.warning("您还没有授权访问，请与管理员联系开通访问权限。");
            rapid("#content-main").children(".J_iframe").attr("src", "");
            rapid("#side-menu").empty();

          } else {
            rapid("#side-menu").append(_initMenusHtml(items, 0));

            setTimeout(function() {
              // 做延时是为了让首页的地图插件能正确显示...
              KIT.openPage("/sysadmin/mymanage");
            }, 1500);
          }
        }
      });
    },
    _bindUpdatePwdEvent = function() {
      rapid("#btnUpdatePwd").on("click", function() {
        rapid("#wndUpdateMyPwd").window({
          title: "修改密码",
          size: "sm",
          buttons: [{
            "确定": _updatePwd
          }],
          onHide: function() {
            rapid("#frmUpdateMyPwd").dataview().bind(null);
          }
        }).show();
      });
    },
    _bindLogoutEvent = function() {
      rapid(".fn-logout").on("click", function() {
        rapid.confirm("您确实要退出吗？", function(e) {
          if(e) {
            window.top.location.href = URL_LOGOUT;
          }
        });
      });
    };

  var _updateTime = function() {
    var __date = new Date();
    rapid("#sysdate").html(rapid.date.parseLongDateString(__date));
    rapid("#systime").html(rapid.date.parseTimeString(__date));
  };

  _loadMenus();

  rapid(function() {
    _updateTime();
    setInterval(function() {
      _updateTime();
    }, 1000);

    _initPwdDv();
    _bindUpdatePwdEvent();
    _bindLogoutEvent();
  });
})(rapid.kit, rapid.res);